import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';

import { User } from './entity/user.entity';
import { UserListReqDto } from './dto/user-list.req.dto';

@Injectable()
export class UserRepository extends Repository<User> {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {
    super(
      userRepository.target,
      userRepository.manager,
      userRepository.queryRunner,
    );
  }

  /**
   * @description 根据 username 查询用户数量
   */
  async countByUsername(username: string): Promise<number> {
    return this.userRepository.count({
      where: { username },
      withDeleted: true,
    });
  }

  /**
   * @description 根据条件查询用户列表（含模糊查询 username）
   * @param dto 查询参数
   * @returns [data, total]
   */
  async findAndCountByConditions(
    dto: UserListReqDto,
  ): Promise<[User[], number]> {
    const { skip, take, username } = dto;

    const queryBuilder = this.userRepository
      .createQueryBuilder('user')
      .leftJoin('user.roles', 'role')
      .groupBy('user.id')
      .skip(skip)
      .take(take);

    if (username) {
      queryBuilder.andWhere('user.username LIKE :username', {
        username: `%${username}%`,
      });
    }

    // 排除角色为超级管理员的用户
    queryBuilder.andWhere(
      () =>
        `user.id NOT IN (
        SELECT user_id FROM user_role_relation
        INNER JOIN roles AS role ON role.id = user_role_relation.role_id
        WHERE role.name = :adminRole
      )`,
      { adminRole: 'admin' },
    );

    const [users, count] = await queryBuilder.getManyAndCount();

    return [users, count];
  }
}
